const axios = (() => {
    if (window.toastr) {
        window.toastr.options.closeButton = true;
    }

    const axios = window.axios.create()
    axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

    axios.interceptors.response.use((response) => {
        toastr.success('请求成功')
        console.log(response)
        return Promise.resolve(response)
    }, (error) => {
        const message = _.get(error, 'response.data.message')
        toastr.error('请求失败<br/>' + message)
        console.warn('errmsg: ' + message)
        return Promise.reject(error)
    })

    return axios
})()


module.exports = ({prefix, uriName}) => {
    function makeUrl(options) {
        const urlPrefix = prefix ? prefix: 'venus'
        if (_.isUndefined(options) || _.isInteger(options)) {
            return _.trimEnd(_.replace(`/${urlPrefix}/${uriName}/${options || ''}`, '//', '/'), '/')
        } else {
            return _.trimEnd(_.replace(`/${options.prefix || urlPrefix}/${options.uriName || uriName}/${options.id || ''}/${options.action || ''}`, '//', '/'), '/')
        }
    }

    return {
        makeUrl,
        axios,
        store(data){
            const url = makeUrl()
            return axios.post(url, data)
        },

        update(id, data){
            const url = makeUrl(id)
            return axios.put(url, data)
        },

        destroy(id){
            const url = makeUrl(id)
            return axios.delete(url)
        },
    }
}